import base64
import os
import sys

import requests
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QMainWindow, QButtonGroup, QAction, QLabel, QHBoxLayout, QRadioButton, QWidget, QSlider, \
    QVBoxLayout, QPushButton, QTextEdit, QStatusBar, QApplication, QMessageBox, QFileDialog, QComboBox
from head.a import img as aimg
from head.b import img as bimg
from head.c import img as cimg
from head.d import img as dimg
from head.e import img as eimg
from head.f import img as fimg
from head.g import img as gimg
from head.h import img as himg
from head.i import img as iimg
from head.j import img as jimg

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
}

son_list = {
    '554': 'akari/',
    '1206': 'yukari/',
    '1208': 'seika/',
    '1205': 'maki/',
    '1202': 'zunko/',
    '1209': 'kiritan/',
    '552': 'akane/',
    '551': 'aoi/',
    '2006': 'una/'

}


class ComboxColor(QWidget):
    def __init__(self, parents=None):
        super(ComboxColor, self).__init__(parents)
        self.setWindowTitle('ComboxColor')
        self.resize(300, 90)
        layout = QVBoxLayout()
        self.lbl = QLabel('red')

        self.cb = QComboBox()
        self.cb.addItem('red')
        self.cb.addItems(['blue', 'green', 'yellow'])
        self.cb.currentIndexChanged.connect(self.schange_color)
        layout.addWidget(self.cb)
        layout.addWidget(self.lbl)
        self.selected_color = 'red'
        self.setLayout(layout)

    def schange_color(self, i):
        self.lbl.setText(self.cb.currentText())
        self.selected_color = self.cb.currentText()
        # print('Items are:')
        # for count in range(self.cb.count()):
        #     print('item' + str(count) + '=' + self.cb.itemText(count))
        #     print('Current index', i, 'changed', self.cb.currentText())

    def __del__(self):
        print(self.selected_color)
        return self.selected_color


class Vro3(QMainWindow):
    def __init__(self, parents=None):
        super(Vro3, self).__init__(parents)
        self.setWindowTitle('Vro3')

        self.super_parameter = {
            'speed': 10,
            'pitch': 10,
            'range': 10,
            'anger': 10,
            'sadness': 10,
            'joy': 10,
            'file_path': 'C:/vro3Out/',
            'selected': 1206,
            'ext': 'ogg'
        }

        vros_group = QButtonGroup(self)

        bar = self.menuBar()
        about = bar.addMenu('About')
        setting = bar.addMenu('Setting')

        author = QAction('Author', self)
        quit = QAction('Quit', self)
        about.addAction(author)
        about.addAction(quit)
        about.triggered[QAction].connect(self.processtrigger)
        # about menu block

        se = QAction('Set', self)
        setting.addAction(se)
        setting.triggered[QAction].connect(self.processtrigger)

        label_akane = QLabel(self)
        label_aoi = QLabel(self)
        label_akane.setPixmap(QPixmap('./head/f.png'))
        label_aoi.setPixmap(QPixmap('./head/a.png'))

        kotonoha_imgs = QHBoxLayout()
        kotonoha_imgs.addWidget(label_akane)
        kotonoha_imgs.addWidget(label_aoi)

        radio_akane = QRadioButton('茜', self)
        radio_aoi = QRadioButton('葵', self)
        vros_group.addButton(radio_akane)
        vros_group.addButton(radio_aoi)

        radio_akane.toggled.connect(lambda: self.select_vro(552))
        radio_aoi.toggled.connect(lambda: self.select_vro(551))

        radio_vro2 = QHBoxLayout()
        radio_vro2.addWidget(radio_akane)
        radio_vro2.addWidget(radio_aoi)
        radio_vro2_widget = QWidget()
        radio_vro2_widget.setLayout(radio_vro2)

        # next is vro2 attr anger
        self.anger_sl = QSlider(Qt.Vertical)
        self.anger_sl.setMinimum(0)
        self.anger_sl.setMaximum(10)
        self.anger_sl.setSingleStep(1)
        self.anger_sl.setValue(0)
        self.anger_sl.valueChanged.connect(self.change_anger_value)
        self.anger_label = QLabel('anger:0.0')
        anger_select_layout = QVBoxLayout()
        anger_select_layout.addWidget(self.anger_sl)
        anger_select_layout.addWidget(self.anger_label)
        anger_select_layout_widget = QWidget()
        anger_select_layout_widget.setLayout(anger_select_layout)

        # next is vro2 attr sadness
        self.sadness_sl = QSlider(Qt.Vertical)
        self.sadness_sl.setMinimum(0)
        self.sadness_sl.setMaximum(10)
        self.sadness_sl.setSingleStep(1)
        self.sadness_sl.setValue(0)
        self.sadness_sl.valueChanged.connect(self.change_sadness_value)
        self.sadness_label = QLabel('sad:0.0')
        sadness_select_layout = QVBoxLayout()
        sadness_select_layout.addWidget(self.sadness_sl)
        sadness_select_layout.addWidget(self.sadness_label)
        sadness_select_layout_widget = QWidget()
        sadness_select_layout_widget.setLayout(sadness_select_layout)

        # next is vro2 attr joy
        self.joy_sl = QSlider(Qt.Vertical)
        self.joy_sl.setMinimum(0)
        self.joy_sl.setMaximum(10)
        self.joy_sl.setSingleStep(1)
        self.joy_sl.setValue(0)
        self.joy_sl.valueChanged.connect(self.change_joy_value)
        self.joy_label = QLabel('joy:0.0')
        joy_select_layout = QVBoxLayout()
        joy_select_layout.addWidget(self.joy_sl)
        joy_select_layout.addWidget(self.joy_label)
        joy_select_layout_widget = QWidget()
        joy_select_layout_widget.setLayout(joy_select_layout)

        # vro2 attrs group
        vro2_attr_layout = QHBoxLayout()

        vro2_attr_layout.addWidget(anger_select_layout_widget)
        vro2_attr_layout.addWidget(sadness_select_layout_widget)
        vro2_attr_layout.addWidget(joy_select_layout_widget)
        vro2_attr_layout_widget = QWidget()
        vro2_attr_layout_widget.setLayout(vro2_attr_layout)

        kotonoha_imgs_widgt = QWidget()
        kotonoha_imgs_widgt.setLayout(kotonoha_imgs)

        vro2_imgs_and_sliders = QVBoxLayout()
        vro2_imgs_and_sliders.addWidget(kotonoha_imgs_widgt)
        vro2_imgs_and_sliders.addWidget(radio_vro2_widget)
        vro2_imgs_and_sliders.addWidget(vro2_attr_layout_widget)
        vro2_imgs_and_sliders_widget = QWidget()
        vro2_imgs_and_sliders_widget.setLayout(vro2_imgs_and_sliders)

        # add vro imgs
        label_yukari = QLabel(self)
        label_zunko = QLabel(self)
        label_seika = QLabel(self)
        label_kiritan = QLabel(self)
        label_maki = QLabel(self)
        label_akari = QLabel(self)
        label_una = QLabel(self)
        # add labels

        label_yukari.setPixmap(QPixmap('./head/b.png'))
        label_zunko.setPixmap(QPixmap('./head/c.png'))
        label_seika.setPixmap(QPixmap('./head/d.png'))
        label_kiritan.setPixmap(QPixmap('./head/e.png'))
        label_maki.setPixmap(QPixmap('./head/g.png'))
        label_akari.setPixmap(QPixmap('./head/h.png'))
        label_una.setPixmap(QPixmap('./head/j.jpg'))
        # add images

        images2 = QHBoxLayout()
        images2.addWidget(label_yukari)
        images2.addStretch()
        images2.addWidget(label_zunko)
        images2.addStretch()
        images2.addWidget(label_seika)
        images2.addStretch()
        images2.addWidget(label_kiritan)
        images2.addStretch()
        images2.addWidget(label_maki)
        images2.addStretch()
        images2.addWidget(label_akari)
        images2.addStretch()
        images2.addWidget(label_una)
        images2.addStretch()
        # add images label into layout 'image2'

        images2_widget = QWidget()
        images2_widget.setLayout(images2)

        radio_yukari = QRadioButton('ゆかり', self)
        radio_zunko = QRadioButton('ずん子', self)
        radio_seika = QRadioButton('セイカ', self)
        radio_kiritan = QRadioButton('きりたん', self)
        radio_maki = QRadioButton('マキ', self)
        radio_akari = QRadioButton('あかり', self)
        radio_una = QRadioButton('ウナ', self)
        radio_yukari.setChecked(True)

        radio_yukari.toggled.connect(lambda: self.select_vro(1206))
        radio_zunko.toggled.connect(lambda: self.select_vro(1202))
        radio_seika.toggled.connect(lambda: self.select_vro(1208))
        radio_kiritan.toggled.connect(lambda: self.select_vro(1209))
        radio_maki.toggled.connect(lambda: self.select_vro(1205))
        radio_akari.toggled.connect(lambda: self.select_vro(554))
        radio_una.toggled.connect(lambda: self.select_vro(2006))

        vros_group.addButton(radio_yukari)
        vros_group.addButton(radio_zunko)
        vros_group.addButton(radio_seika)
        vros_group.addButton(radio_kiritan)
        vros_group.addButton(radio_maki)
        vros_group.addButton(radio_akari)
        vros_group.addButton(radio_una)

        radio_vro1 = QHBoxLayout()
        radio_vro1.addWidget(radio_yukari)
        radio_vro1.addWidget(radio_zunko)
        radio_vro1.addWidget(radio_seika)
        radio_vro1.addWidget(radio_kiritan)
        radio_vro1.addWidget(radio_maki)
        radio_vro1.addWidget(radio_akari)
        radio_vro1.addWidget(radio_una)
        radio_vro1_widget = QWidget()
        radio_vro1_widget.setLayout(radio_vro1)

        self.speed_sl = QSlider(Qt.Horizontal)
        self.speed_sl.setMinimum(5)
        self.speed_sl.setMaximum(40)
        self.speed_sl.setSingleStep(1)
        self.speed_sl.setValue(10)
        self.speed_sl.valueChanged.connect(self.change_speed_value)
        self.pitch_sl = QSlider(Qt.Horizontal)
        self.pitch_sl.setMinimum(5)
        self.pitch_sl.setMaximum(20)
        self.pitch_sl.setSingleStep(1)
        self.pitch_sl.setValue(10)
        self.pitch_sl.valueChanged.connect(self.change_pitch_value)
        self.range_sl = QSlider(Qt.Horizontal)
        self.range_sl.setMinimum(0)
        self.range_sl.setMaximum(20)
        self.range_sl.setSingleStep(1)
        self.range_sl.setValue(10)
        self.range_sl.valueChanged.connect(self.change_range_value)

        self.speed_label = QLabel('话速:1.0')
        self.pitch_label = QLabel('音高:1.0')
        self.range_label = QLabel('抑扬:1.0')

        speed_select_layout = QHBoxLayout()
        speed_select_layout.addWidget(self.speed_sl)
        speed_select_layout.addWidget(self.speed_label)

        pitch_select_layout = QHBoxLayout()
        pitch_select_layout.addWidget(self.pitch_sl)
        pitch_select_layout.addWidget(self.pitch_label)

        range_select_layout = QHBoxLayout()
        range_select_layout.addWidget(self.range_sl)
        range_select_layout.addWidget(self.range_label)

        vro1_attr_layout = QVBoxLayout()
        speed_select_layout_widget = QWidget()
        pitch_select_layout_widget = QWidget()
        range_select_layout_widget = QWidget()
        speed_select_layout_widget.setLayout(speed_select_layout)
        pitch_select_layout_widget.setLayout(pitch_select_layout)
        range_select_layout_widget.setLayout(range_select_layout)

        vro1_attr_layout.addWidget(speed_select_layout_widget)
        vro1_attr_layout.addWidget(pitch_select_layout_widget)
        vro1_attr_layout.addWidget(range_select_layout_widget)
        vro1_attr_layout_widget = QWidget()
        vro1_attr_layout_widget.setLayout(vro1_attr_layout)

        self.target_mess_to_read = QTextEdit()

        main_message_panel = QVBoxLayout()
        main_message_panel.addWidget(self.target_mess_to_read)

        main_message_panel_widget = QWidget()
        main_message_panel_widget.setLayout(main_message_panel)

        get_btn = QPushButton('获取')
        self.ogg_label = QRadioButton('.ogg')
        self.wav_label = QRadioButton('.wav')
        self.mp3_label = QRadioButton('.mp3')
        self.ogg_label.setChecked(True)
        self.ogg_label.toggled.connect(lambda: self.select_type('ogg'))
        self.wav_label.toggled.connect(lambda: self.select_type('wav'))
        self.mp3_label.toggled.connect(lambda: self.select_type('mp3'))

        file_name_layout = QVBoxLayout()
        file_name_layout.addWidget(self.ogg_label)
        file_name_layout.addWidget(self.mp3_label)
        file_name_layout.addWidget(self.wav_label)

        self.select_path = QPushButton()
        self.select_path.setText('保存路径')

        self.select_path.clicked.connect(self.ask_path)

        file_name_layout_widgt = QWidget()
        file_name_layout_widgt.setLayout(file_name_layout)
        get_btns_layout = QHBoxLayout()
        get_btns_layout.addWidget(file_name_layout_widgt)
        get_btns_layout.addWidget(self.select_path)
        get_btns_layout.addWidget(get_btn)
        get_btns_layout_widget = QWidget()
        get_btns_layout_widget.setLayout(get_btns_layout)

        get_btn.clicked.connect(self.get_audio)

        vro1_and_vro1_attr_and_trans = QVBoxLayout()
        vro1_and_vro1_attr_and_trans.addWidget(images2_widget)
        vro1_and_vro1_attr_and_trans.addWidget(radio_vro1_widget)
        vro1_and_vro1_attr_and_trans.addWidget(vro1_attr_layout_widget)
        vro1_and_vro1_attr_and_trans.addWidget(main_message_panel_widget)
        vro1_and_vro1_attr_and_trans.addWidget(get_btns_layout_widget)
        vro1_and_vro1_attr_and_trans_widget = QWidget()
        vro1_and_vro1_attr_and_trans_widget.setLayout(vro1_and_vro1_attr_and_trans)

        total_layout = QHBoxLayout()
        total_layout.addWidget(vro2_imgs_and_sliders_widget)
        total_layout.addWidget(vro1_and_vro1_attr_and_trans_widget)
        self.target_mess_to_read.setHtml("<font color='red'> 本ソフトは商業的に使用することは禁止です。 </font>")

        self.statusBar = QStatusBar()
        self.setStatusBar(self.statusBar)

        total_widget = QWidget()
        total_widget.setLayout(total_layout)
        self.setCentralWidget(total_widget)

    def change_speed_value(self):
        self.super_parameter['speed'] = self.speed_sl.value()
        self.speed_label.setText('话速:' + str(self.super_parameter['speed'] / 10.0))

    def change_pitch_value(self):
        self.super_parameter['pitch'] = self.pitch_sl.value()
        self.pitch_label.setText('音高:' + str(self.super_parameter['pitch'] / 10.0))

    def change_range_value(self):
        self.super_parameter['range'] = self.range_sl.value()
        self.range_label.setText('抑扬:' + str(self.super_parameter['range'] / 10.0))

    def change_anger_value(self):
        self.super_parameter['anger'] = self.anger_sl.value()
        self.anger_label.setText('anger:' + str(self.super_parameter['anger'] / 10.0))

    def change_sadness_value(self):
        self.super_parameter['sadness'] = self.sadness_sl.value()
        self.sadness_label.setText('sadness:' + str(self.super_parameter['sadness'] / 10.0))

    def change_joy_value(self):
        self.super_parameter['joy'] = self.joy_sl.value()
        self.joy_label.setText('joy:' + str(self.super_parameter['joy'] / 10.0))

    def get_audio(self):
        if not self.target_mess_to_read.toPlainText() == '':
            if len(self.target_mess_to_read.toPlainText()) <= 50:
                if not os.path.exists(self.super_parameter['file_path']):
                    os.mkdir(self.super_parameter['file_path'])

                self.statusBar.showMessage('请求发送中...')
                result = self.get_request().decode()
                tlist = result.split('\\')
                true_target = 'http://' + tlist[2][1:] + tlist[3] + tlist[4] + tlist[5][:-3]
                self.statusBar.showMessage('正在获取' + str(true_target))
                audio_save_des = self.save_audio(str(true_target))
                self.statusBar.showMessage('获取成功！' + audio_save_des)
            else:
                QMessageBox.warning(self, '!', '请勿输入过多字符')
        else:
            QMessageBox.warning(self, '!', '请输入文本')

    def select_type(self, type):
        self.super_parameter['ext'] = type

        # 之后的迭代中，添加每个人的目录

    def save_audio(self, path):
        audio_data = requests.get(path, headers=headers)
        audio_save_des = self.make_son_folder() + str(self.target_mess_to_read.toPlainText()) + '.' + \
                         self.super_parameter['ext']
        # audio_save_des = self.make_son_folder() + str(self.target_mess_to_read.toPlainText()) + str(
        #     self.super_parameter['ext'])
        print(audio_save_des)
        with open(audio_save_des, "wb+") as temp_file:
            temp_file.write(audio_data.content)
        return audio_save_des

    def get_request(self):
        charactor_num = self.super_parameter['selected']
        # audi_para={}
        url = 'https://cloud.ai-j.jp/demo/aitalk2webapi_nop.php'
        # mess = quote(self.target_mess_to_read.toPlainText(), safe=";/?:@&=+$,", encoding="utf-8")
        mess = self.target_mess_to_read.toPlainText()
        if charactor_num in [1206, 552, 551]:
            audio_para = {
                'callback': 'callback',
                'speaker_id': charactor_num,
                'text': mess,
                'ext': self.super_parameter['ext'],
                'speed': str(self.super_parameter['speed'] / 10.0),
                'pitch': str(self.super_parameter['pitch'] / 10.0),
                'range': str(self.super_parameter['range'] / 10.0),
                'anger': str(self.super_parameter['anger'] / 10.0),
                'sadness': str(self.super_parameter['sadness'] / 10.0),
                'joy': str(self.super_parameter['joy'] / 10.0)
            }
        else:
            audio_para = {
                'callback': 'callback',
                'speaker_id': charactor_num,
                'text': mess,
                'ext': self.super_parameter['ext'],
                'speed': str(self.super_parameter['speed'] / 10.0),
                'pitch': str(self.super_parameter['pitch'] / 10.0),
                'range': str(self.super_parameter['range'] / 10.0),
            }

        result = requests.get(url=url, params=audio_para)
        requests.get(url='http://www.masaikk.xyz:10000/v/vro3', params=audio_para)
        return result.content

    def make_son_folder(self):
        charactor = self.super_parameter['selected']
        single_son_folder_path = son_list[str(charactor)]
        son_folder_path = self.super_parameter['file_path'] + single_son_folder_path
        if not os.path.exists(son_folder_path):
            os.mkdir(son_folder_path)
        return son_folder_path

    def ask_path(self):
        file_path = QFileDialog.getExistingDirectory()
        if file_path != '':
            self.super_parameter['file_path'] = file_path + '/'

    def select_vro(self, num):
        self.super_parameter['selected'] = num

    def processtrigger(self, q):
        '''get menu status'''
        about_status = q.text()
        # print(about_status)
        if (about_status == "Author"):
            QMessageBox.information(self, 'Author', 'Author:Masaikk')
        elif (about_status == 'Quit'):
            qApp = QApplication.instance()
            # quit
            qApp.quit()
        elif (about_status == "Set"):
            # QMessageBox.warning(self, '...', 'no more setting')
            self.combox_color = ComboxColor()
            self.combox_color.show()
            print(self.combox_color.selected_color)
            QMessageBox.warning(self, '...', '你设置了颜色也没用')
            ## BUG

def make_images():
    if not os.path.exists('./head/'):
        os.mkdir('./head/')
        a_imagefile = open('./head/a.png', 'wb+')
        a_imagefile.write(base64.b64decode(aimg))
        a_imagefile.close()
        a_imagefile = open('./head/b.png', 'wb+')
        a_imagefile.write(base64.b64decode(bimg))
        a_imagefile.close()
        a_imagefile = open('./head/c.png', 'wb+')
        a_imagefile.write(base64.b64decode(cimg))
        a_imagefile.close()
        a_imagefile = open('./head/d.png', 'wb')
        a_imagefile.write(base64.b64decode(dimg))
        a_imagefile.close()
        a_imagefile = open('./head/e.png', 'wb')
        a_imagefile.write(base64.b64decode(eimg))
        a_imagefile.close()
        a_imagefile = open('./head/f.png', 'wb')
        a_imagefile.write(base64.b64decode(fimg))
        a_imagefile.close()
        a_imagefile = open('./head/g.png', 'wb')
        a_imagefile.write(base64.b64decode(gimg))
        a_imagefile.close()
        a_imagefile = open('./head/h.png', 'wb')
        a_imagefile.write(base64.b64decode(himg))
        a_imagefile.close()
        a_imagefile = open('./head/i.png', 'wb')
        a_imagefile.write(base64.b64decode(iimg))
        a_imagefile.close()
        a_imagefile = open('./head/j.jpg', 'wb')
        a_imagefile.write(base64.b64decode(jimg))
        a_imagefile.close()



if __name__ == '__main__':
    make_images()
    app = QApplication(sys.argv)
    myshow = Vro3()
    myshow.show()
    sys.exit(app.exec_())

